package com.leo.cloud.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 文件名：HttpUtil.java
 *
 * http请求工具类
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 判断http请求是否成功
     * @param url
     * @return
     */
    public static boolean checkHttpRequestStatus(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }
    /**
     * 文件名：HttpUtil.java
     * @create 2018-06-19 9:52
     * @create by Dibbing pan
     *
     * @Description: http请求..
     * @Param urlStr 请求地址
     * @Param params 参数
     * @Param proxy 代理.
     * @Param is post  是post请求,否get请求.
     */
    public static String request(String urlStr, Map<String,String> params, Proxy proxy,boolean isPost) throws Exception{
        String param = getParamStr(params);
        System.out.println("map = "+ JSON.toJSONString(params)+"\nparamstr="+param+"\nurl="+urlStr);
        //创建链接
        URL url = new URL(urlStr);
        HttpURLConnection conn;
        if(null != proxy){
            conn = (HttpURLConnection) url.openConnection(proxy);
        }else{
            conn = (HttpURLConnection)url.openConnection();
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //根据传参方式进行配置 post的情况下，需要通过流写入post参数
        if (isPost) {
            conn.setRequestMethod("POST");
        }else{
            conn.setRequestMethod("GET");
        }
        OutputStream out = conn.getOutputStream();
        out.write(param.getBytes("UTF-8"));

        //读取反馈数据
        StringBuilder sb = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String str = null;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        conn.disconnect();
        if (in != null) {
            in.close();
        }
        return sb.toString();
    }
    /**
     * 文件名：HttpUtil.java
     * @create 2018-06-19 9:52
     * @create by Dibbing pan
     *
     * @Description: http请求..
     * @Param urlStr 请求地址
     * @Param params 参数
     * @Param proxy 代理.
     * @Param is post  是post请求,否get请求.
     */
    public static String request(String urlStr, String param, Proxy proxy,boolean isPost) throws Exception{
        //创建链接
        URL url = new URL(urlStr);
        HttpURLConnection conn;
        if(null != proxy){
            conn = (HttpURLConnection) url.openConnection(proxy);
        }else{
            conn = (HttpURLConnection)url.openConnection();
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json;application/x-www-form-urlencoded;charset=utf-8");
        //根据传参方式进行配置 post的情况下，需要通过流写入post参数
        if (isPost) {
            conn.setRequestMethod("POST");
        }else{
            conn.setRequestMethod("GET");
        }
        if(!StringUtils.isBlank(param)) {
            OutputStream out = conn.getOutputStream( );
            out.write(param.getBytes("UTF-8"));
        }
        //读取反馈数据
        StringBuilder sb = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String str = null;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        conn.disconnect();
        if (in != null) {
            in.close();
        }
        param = sb.toString();
//        ThirdSystem.out.println("------请求地址---------->"+urlStr+"\n"+"------返回结果------->"+param);
        return param;
    }
    /**
     * @Author: Dibbing pan
     * @Date: 2018-05-09 13:41
     * @Description : 调用https接口....
     * @return:
     */
    public static String requestIgnoreSSL(String urlStr, Map<String,String> params, Proxy proxy,boolean isPost) throws Exception{
        String param = getParamStr(params);
        System.out.println("map = "+param+",paramstr"+param+"\nurl="+urlStr);
        return request(urlStr,param,proxy,isPost);
//
//        HttpsURLConnection.setDefaultHostnameVerifier(new HttpUtil().new NullHostNameVerifier());
//        SSLContext sc = SSLContext.getInstance("TLS");
//        sc.init(null, trustAllCerts, new SecureRandom());
//        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//        URL url = new URL(urlStr);
//        // 打开restful链接
//        HttpURLConnection conn;
//        if(null != proxy){
//            conn = (HttpURLConnection) url.openConnection(proxy);
//        }else{
//            conn = (HttpURLConnection)url.openConnection();
//        }
//        conn.setDoOutput(true);
//        conn.setDoInput(true);
//        // 设置访问提交模式，表单提交
//        if (isPost) {
//            conn.setRequestMethod("POST");
//        }else{
//            conn.setRequestMethod("GET");
//        }
//        OutputStream out = conn.getOutputStream();
//        out.write(param.getBytes("UTF-8"));
//
//        // 读取请求返回值
//        StringBuilder sb = new StringBuilder();
//        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
//        String str = null;
//        while ((str = in.readLine()) != null) {
//            sb.append(str);
//        }
//        conn.disconnect();
//        if (in != null) {
//            in.close();
//        }
//        return sb.toString();
    }

    static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    public class NullHostNameVerifier implements HostnameVerifier {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    }
    /**
     * @Author: Dibbing pan
     * @Date: 2018-05-09 12:21
     * @Description : 从map中获取参数,并返回
     * @return:
     */
    public static String getParamStr(Map<String,String> params){
        String paramStr = "";
        if(null != params && !params.isEmpty()){
            java.util.Iterator<Map.Entry<String,String>> entries = params.entrySet().iterator();
            while (entries.hasNext()){
                Map.Entry<String,String> entrySet = entries.next();
                String p = entrySet.getKey()+"="+entrySet.getValue();
                System.out.println("参数:"+p);
                if(paramStr.equals("")){
                    paramStr = p;
                }else{
                    paramStr += ("&"+p);
                }
            }
        }
        return paramStr;
    }



    /**
     * @Author: Dibbing pan
     * @Date: 2018-04-04 11:24
     * @Description : 流写出字符串
     * @return:
     */
    public static String postJsonStr(String postUrl,Proxy proxy, String jsonData) {
        try {
//            String log = "\n-------------->postJsonStr postUrl="+postUrl+"\n---------------->postData="+jsonData;
//            logger.error(log);
            URL url = new URL(postUrl);

            url.openConnection();
            HttpURLConnection conn;
            if(null != proxy){
                conn = (HttpURLConnection) url.openConnection(proxy);
            }else{
                conn = (HttpURLConnection)url.openConnection();
            }
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setConnectTimeout(1000);
            conn.usingProxy();
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Length", "" + jsonData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(jsonData);
            out.flush();
            out.close();
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                String line, result = "";
                if(conn.getResponseCode()>300){
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                    while ((line = in.readLine()) != null) {
                        result += line + "\n";
                    }
                    in.close();
//                    log += "\n-----------------------> "+result;
//                    logger.error(log);
                }else{
//                    log += "\n---------------->connect failed!";
//                    logger.error(log);
                }
                return result;
            }
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
//            log += "\n-----------------------> "+result;
//            logger.error(log);
            return result;
        } catch (Exception e) {
             e.printStackTrace();
        }
        return "";
    }


    public static String httpPostForm(String url, Map<String, String> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        System.out.println("send_url:" + url);
        System.out.println("send_data:" + sb.toString());
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }
}
